import json
import requests
from PySide2 import QtCore, QtWidgets
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QWidget, QVBoxLayout, QPushButton, QHBoxLayout, QLabel, QLineEdit, QComboBox

# 模板位置改变窗口
from requests_toolbelt import MultipartEncoder

import share
from binding import template_bind, original_bind
from util import fileSelect
from util.ComboBoxUtil import ComboBoxUtil


class template_move_window(QWidget):
    def __init__(self,id ,parent=None):
        super(template_move_window, self).__init__(parent)
        self.setStyleSheet("""
            background-color: rgb(255, 255, 255);
        """)
        # 设置窗口大小
        self.setFixedSize(200, 100);
        # 设置题头
        self.setWindowTitle("更改模板位置")
        # 隐藏最大化最小化
        self.setWindowFlags(Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint | QtCore.Qt.WindowStaysOnTopHint)

        # 添加框组件绑定（任务名，备注） 最大总体布局为纵向布局
        vLayout = QVBoxLayout()
        # 创建填写布局
        # 新建按钮组
        buttons = self.move_buttons(id)
        param_body = self.param_body()
        vLayout.addWidget(param_body)
        vLayout.addWidget(buttons)
        self.setLayout(vLayout)

        # 新建保存按钮组
    def move_buttons(self,id):
        widget = QWidget()
        # 确定
        confirmBtn = QPushButton('确定',self)
        confirmBtn.setStyleSheet(''' text-align : center;
                                        background-color : #2B77CF;
                                        height : 25px;
                                        border-style: outset;
                                        padding:0 15px;
                                        font : 13px; ''')

        confirmBtn.clicked.connect(lambda : self.confirmClick(id))

        # 取消
        cancelBtn = QPushButton('取消')
        cancelBtn.setStyleSheet(''' text-align : center;
                                        background-color : #D20A0A;
                                        height : 25px;
                                        border-style: outset;
                                        padding:0 15px;
                                        font : 13px; ''')

        cancelBtn.clicked.connect(lambda : self.close())

        # 确认删除按钮布局
        hLayout = QHBoxLayout()
        hLayout.setObjectName("buttonLayout")
        hLayout.addStretch();
        hLayout.addWidget(confirmBtn)
        hLayout.addWidget(cancelBtn)
        hLayout.setContentsMargins(5,2,5,2)
        widget.setLayout(hLayout)
        return widget

    # 确定修改位置
    def confirmClick(self,id):
        # 查询分组及单位
        from binding.home_bind import home_bind
        ug = home_bind().get_ug_comboBox_fun()
        url = share.RURL.backendUrl + "/template/alterRow/" + str(id) + "/" + self.row_num_LineEdit.text() + "/" + ug["group_value"] + "/" + ug["unit_value"]
        requests.encoding = 'utf-8'
        result = requests.request(method="PUT", url=url, headers=share.token.headers)
        dataMap = json.loads(result.text)

        try:
            if dataMap["flag"] == True:
                QtWidgets.QMessageBox.about(self, "信息提示框", dataMap["message"])
                self.close()
                template_bind.bind().findAll()
        except:
            QtWidgets.QMessageBox.about(self, "信息提示框", "位置修改失败")

    # 位置组件
    def param_body(self):
        widget = QWidget()
        str1 = QLabel("将模板调整至:")
        # 行号
        self.row_num_LineEdit = QLineEdit(self)
        str2 = QLabel("行")
        # 进行任务名及填写框布局
        hLayout1 = QHBoxLayout()
        hLayout1.addWidget(str1)
        hLayout1.addWidget(self.row_num_LineEdit)
        hLayout1.addWidget(str2)

        widget.setLayout(hLayout1)
        return widget

# 源数据上传参数弹窗
class original_uploading(QWidget):
    def __init__(self,parent=None):
        super(original_uploading, self).__init__(parent)
        # 设置窗口大小
        self.setFixedSize(200, 250);
        # 设置题头
        self.setWindowTitle("原表上传")
        # 隐藏最大化最小化
        self.setWindowFlags(Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint | QtCore.Qt.WindowStaysOnTopHint)
        # 添加框组件绑定（任务名，备注） 最大总体布局为纵向布局
        vLayout = QVBoxLayout()
        # 创建填写布局
        # 文件
        vLayout.addWidget(self.file_module())
        # 期间
        vLayout.addWidget(self.period_module())
        # 编码
        vLayout.addWidget(self.code_module())
        # 分类
        vLayout.addWidget(self.group_module())
        # 创建按钮组（确定，取消）
        vLayout.addWidget(self.buttons())
        self.setLayout(vLayout)

    # 文件
    def file_module(self):
        widget = QWidget()
        # 任务名
        file_label = QPushButton()
        file_label.setText("文件")
        file_label.setStyleSheet(''' text-align : center;
                                    background-color : transparent;
                                    height : 25px;
                                    width : 25px;
                                    border-style: outset;
                                    padding:0 0;
                                    font : 13px; ''')

        # 点击选择文件地址
        file_label.clicked.connect(lambda : self.file_select())

        # 创建任务名填写框
        file_LineEdit = QLineEdit(self)
        self.file_LineEdit = file_LineEdit
        file_LineEdit.setObjectName("file_LineEdit")
        # 进行任务名及填写框布局
        hLayout1 = QHBoxLayout()
        hLayout1.addWidget(file_label)
        hLayout1.addWidget(file_LineEdit)

        widget.setLayout(hLayout1)
        return widget

    # 期间
    def period_module(self):
        widget = QWidget()
        # 任务名
        period_label = QLabel()
        period_label.setText("期间")
        # 创建任务名填写框
        period_LineEdit = QLineEdit(self)
        self.period_LineEdit = period_LineEdit
        period_LineEdit.setObjectName("period_LineEdit")
        # 进行任务名及填写框布局
        hLayout1 = QHBoxLayout()
        hLayout1.addWidget(period_label)
        hLayout1.addWidget(period_LineEdit)

        widget.setLayout(hLayout1)
        return widget

    # 编码
    def code_module(self):
        widget = QWidget()
        code_label = QLabel()
        code_label.setText("编码")
        # 创建任务名填写框
        code_LineEdit = QLineEdit(self)
        self.code_LineEdit = code_LineEdit
        code_LineEdit.setObjectName("code_LineEdit")
        # 进行任务名及填写框布局
        hLayout1 = QHBoxLayout()
        hLayout1.addWidget(code_label)
        hLayout1.addWidget(code_LineEdit)

        widget.setLayout(hLayout1)
        return widget

    # 分类
    def group_module(self):
        widget = QWidget()
        # 任务名
        group_label = QLabel()
        group_label.setText("分类")
        # 创建任务名填写框
        group_QComboBox = QComboBox(self)
        self.group_QComboBox = group_QComboBox
        group_QComboBox.setObjectName("group_QComboBox")
        # 进行任务名及填写框布局
        hLayout1 = QHBoxLayout()
        hLayout1.addWidget(group_label)
        hLayout1.addWidget(group_QComboBox)

        widget.setLayout(hLayout1)
        return widget

    # 确定取消按钮组
    def buttons(self):
        widget = QWidget()
        # 确定
        confirmBtn = QPushButton('确定',self)
        confirmBtn.setStyleSheet(''' text-align : center;
                                    background-color : transparent;
                                    height : 25px;
                                    border-style: outset;
                                    padding:0 15px;
                                    font : 13px; ''')

        confirmBtn.clicked.connect(lambda : self.create_group_confirm())

        # 取消
        cancelBtn = QPushButton('取消')
        cancelBtn.setStyleSheet(''' text-align : center;
                                    background-color : transparent;
                                    height : 25px;
                                    border-style: outset;
                                    padding:0 15px;
                                    font : 13px; ''')

        cancelBtn.clicked.connect(self.close)

        # 确认删除按钮布局
        hLayout = QHBoxLayout()
        hLayout.setObjectName("buttonLayout")
        hLayout.addStretch();
        hLayout.addWidget(confirmBtn)
        hLayout.addWidget(cancelBtn)
        hLayout.setContentsMargins(5,2,5,2)
        widget.setLayout(hLayout)
        return widget

    # 文件地址选择
    def file_select(self):
        # 选择源数据位置
        data_address = fileSelect.file_address()
        self.file_LineEdit.setText(data_address)

    # 新建分组事件
    def create_group_confirm(self):
        period = self.findChild(QLineEdit,"period_LineEdit").text()
        code = self.findChild(QLineEdit,"code_LineEdit").text()
        data_address = self.findChild(QLineEdit,"file_LineEdit").text()
        groupID = ComboBoxUtil(self.findChild(QComboBox,"group_QComboBox")).getValue()


        # 准备上传数据
        file_name = data_address[fileSelect.find_last(data_address, "\\"):]
        url = share.RURL.backendUrl + "/original/originalImport"
        # 准备文件
        files = MultipartEncoder({
            'file': (file_name, open(data_address, 'rb'), 'application/vnd.ms-excel'),
        })
        # 准备参数
        param = {"period":period,
                 "code": code,
                 "group": str(groupID),}
        # 准备数据头
        headers = share.token.headers
        headers['Content-Type'] = files.content_type
        # 发送请求
        result = requests.request(method="POST", url=url, params=param, data=files,headers=headers, verify=False)
        dataMap = json.loads(result.text)



        if "flag" in dataMap.keys():
            self.close()
            QtWidgets.QMessageBox.about(share.SI.main.ui ,"信息提示框", dataMap["message"])
            # 查询头元数据列表
            original_bind.bind().findAll()
        else:
            self.close()
            QtWidgets.QMessageBox.about(share.SI.main.ui ,"信息提示框", "提交源数据失败")